import React, {Component} from 'react';
import {
    StyleSheet,
    TouchableOpacity,
    Image,
    InteractionManager
} from 'react-native';
import {Toast} from 'teaset'
import {View, Text, Button} from 'react-native-ui-lib'
import {HeaderBackButton} from 'react-navigation'
import DateTimePicker from 'react-native-modal-datetime-picker';
import format from 'date-fns/format'


import colors from "../common/colors";
import Global from '../common/global'
import Util from '../common/util'
import Api from '../common/api'
import Loading from '../common/LoadingModal'


export default class YuBaoDetail extends Component {

    static navigationOptions = ({navigation, screenProps}) => ({
        header: null
    })

    constructor(props) {
        super(props);
        let {X, Y, type, title} = this.props.navigation.state.params
        this.X = X
        this.Y = Y
        this.type = type
        this.state = {
            isLoading: false,
            selectedX: X[0].imgX,
            selectedY: Y[0].imgY,
            img_path: '',
            date: title,
            isDateTimePickerVisible : false
        };
    }

    componentDidMount() {
        InteractionManager.runAfterInteractions(() => {
            this.reload()
        })
    }

    changeLoadingStatus = (flag) => {
        this.setState({
            isLoading: flag
        })
    }

    reload = () => {
        this.changeLoadingStatus(true)
        Util.fetchPost(Api.shuzhiDetail, {
            type: this.type,
            imgX: this.state.selectedX,
            imgY: this.state.selectedY,
            date: this.state.date
        })
            .then(({code, msg, data}) => {
                this.changeLoadingStatus(false)
                if (code == '0') {
                    this.setState({
                        img_path: data.img_path
                    })
                } else {
                    Toast.fail(msg)
                }
            }).catch(error => {
            this.changeLoadingStatus(false)
            console.log(error)
        });
    }

    pressX = async (v) => {
        await this.setState({
            selectedX: v.imgX
        })
        this.reload()
    }

    renderX = () => {

        return (
            <View height={50} row centerV style={{backgroundColor: colors.bgColor}}>
                {
                    this.X.map((v, i) => {
                            let borderX = this.state.selectedX == v.imgX ? {
                                borderBottomColor: '#176DD7',
                                borderBottomWidth: 2
                            } : {}
                            let color = this.state.selectedX == v.imgX ? '#176DD7' : '#333333'
                            return (
                                <TouchableOpacity key={"X" + i} style={{flex: 1}} activeOpacity={0.8}
                                                  onPress={() => this.pressX(v)}>
                                    <View flex
                                          style={[{backgroundColor: '#F7F7F7'}, borderX]}
                                          center>
                                        <Text text85 center style={{color}}>{v.name}</Text>
                                    </View>
                                </TouchableOpacity>
                            )
                        }
                    )
                }
            </View>
        )
    }

    pressY = async (v) => {
        await this.setState({
            selectedY: v.imgY
        })
        this.reload()
    }

    renderY = () => {
        return (
            <View width={50} column centerH style={{backgroundColor: colors.bgColor}}>
                {
                    this.Y.map((v, i) => {
                            let borderY = this.state.selectedY == v.imgY ? {
                                borderLeftColor: '#176DD7',
                                borderLeftWidth: 2
                            } : {}
                            let color = this.state.selectedY == v.imgY ? '#176DD7' : '#333333'
                            return (
                                <TouchableOpacity key={"Y" + i} style={{flex: 1, width: 50}} activeOpacity={0.8}
                                                  onPress={() => this.pressY(v)}>
                                    <View flex
                                          style={[{backgroundColor: '#F7F7F7'}, borderY]}
                                          center>
                                        <Text text85 style={{color}}>{v.name}</Text>
                                    </View>
                                </TouchableOpacity>
                            )
                        }
                    )
                }
            </View>
        )
    }

    renderImg = () => {
        return (
            <View flex>
                {
                    this.state.img_path ? (
                        <Image
                            style={{
                                width: Global.width - 50,
                                height: Global.width - 50
                            }}
                            source={{uri: this.state.img_path}}
                        />
                    ) : null
                }
            </View>
        )
    }

    pressDate = () => {
        this._showDateTimePicker()
    }

    renderHeader = () => {
        return (
            <View height={Global.headerHeight}
                  style={{paddingTop: Global.paddingTop, justifyContent: 'space-between', backgroundColor : colors.headerBg}}
                  row centerV
            >
                <HeaderBackButton
                    onPress={() => {
                        this.props.navigation.goBack()
                    }}
                    tintColor={"#fff"}
                />
                <Button
                    link
                    label={this.state.date}
                    labelStyle={{fontSize: 16, color: '#fff', fontWeight : 'bold'}}
                    onPress={this.pressDate}
                />
                <View width={50}/>
            </View>
        )
    }

    _showDateTimePicker = () => this.setState({ isDateTimePickerVisible: true });

    _hideDateTimePicker = () => this.setState({ isDateTimePickerVisible: false });

    _handleDatePicked = async(date) => {
        console.log('A date has been picked: ', date);
        this._hideDateTimePicker();
        let dateStr = format(date, 'YYYY-MM-DD')
        await this.setState({
            date : dateStr
        })
        this.reload()
    };

    render() {
        return (
            <View style={styles.container}>
                {this.renderHeader()}
                {this.renderX()}
                <View row height={Global.width - 50}>
                    {this.renderY()}
                    {this.renderImg()}
                </View>
                <DateTimePicker
                    isVisible={this.state.isDateTimePickerVisible}
                    onConfirm={this._handleDatePicked}
                    onCancel={this._hideDateTimePicker}
                    mode={"date"}
                    titleIOS={"选择日期"}
                    cancelTextIOS={"关闭"}
                    confirmTextIOS={"确定"}
                />
                <Loading isOpen={this.state.isLoading}/>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
    },
});
